package com.whfc.ms.api.mach.controller.v1;

import com.whfc.common.result.ListData;
import com.whfc.common.result.PageData;
import com.whfc.common.result.Result;
import com.whfc.common.result.ResultUtil;
import com.whfc.common.util.AssertUtil;
import com.whfc.common.util.DateUtil;
import com.whfc.common.util.SessionAttr;
import com.whfc.entity.dto.msg.AppWarnMsgRecDTO;
import com.whfc.fuum.entity.SysUser;
import com.whfc.mach.dto.AppMachDTO;
import com.whfc.mach.dto.warn.AppMachWarnCountDTO;
import com.whfc.mach.dto.warn.AppWarnDetailDTO;
import com.whfc.mach.dto.warn.AppWarnMachRecordDTO;
import com.whfc.mach.dto.warn.AppWarnRuleDTO;
import com.whfc.mach.param.warn.*;
import com.whfc.ms.api.mach.service.MsMachWarnService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * @author sun_guodong
 * @description 设备报警
 * @date 2020-11-19
 */
@RequiresPermissions("mach/warn")
@RestController
@RequestMapping("/ms/api/v1/mach/warn")
public class MsMachWarnController {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MsMachWarnService msWarnService;

    @GetMapping("/warnNumStatic")
    public Result warnNumStatic(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                                @RequestParam("deptId") Integer deptId,
                                @RequestParam("state") Integer state,
                                @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "startDate", required = false) Date startDate,
                                @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "endDate", required = false) Date endDate) {
        logger.info("设备报警次数统计,loginer:{},deptId:{},state:{},startDate:{},endDate:{}",
                user.getUsername(), deptId, state, startDate, endDate);
        Date startTime = null;
        Date endTime = null;
        if (startDate != null) {
            startTime = DateUtil.getDateBegin(startDate);
        }
        if (endDate != null) {
            endTime = DateUtil.getDateEnd(endDate);
        }
        AppMachWarnCountDTO data = msWarnService.warnNumStatic(deptId, state, startTime, endTime);
        return ResultUtil.success(data);
    }

    @GetMapping("/rule/list")
    public Result ruleList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                           @RequestParam("pageNum") Integer PageNum,
                           @RequestParam("pageSize") Integer pageSize,
                           @RequestParam(value = "ruleType", required = false) Integer ruleType,
                           @RequestParam(value = "keyword", required = false) String keyword,
                           @RequestParam("deptId") Integer deptId,
                           @RequestParam(value = "enableFlag", required = false) Integer enableFlag) {
        logger.info("设备报警设置列表，loginer:{},pageNum:{},pageSize:{},ruleType:{},keyword:{},enableFlag:{}", user.getUsername(), PageNum, pageSize, ruleType, keyword, enableFlag);
        PageData<AppWarnRuleDTO> pageData = msWarnService.ruleList(PageNum, pageSize, ruleType, keyword, deptId, enableFlag);
        return ResultUtil.success(pageData);
    }

    @RequiresPermissions("mach/warn/setting/del")
    @PostMapping("/rule/del/{ruleId}")
    public Result ruleDel(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                          @PathVariable("ruleId") Integer ruleId) {
        logger.info("删除设备报警规则，loginer:{},ruleId:{}", user.getUsername(), ruleId);
        msWarnService.ruleDel(ruleId);
        return ResultUtil.success();
    }

    @RequiresPermissions(value = {"mach/warn/setting/enable", "mach/warn/setting/disable"}, logical = Logical.OR)
    @PostMapping("/rule/enable")
    public Result enable(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                         @RequestBody @Validated AppWarnEnableParam request) {
        logger.info("启用禁用报警，loginer:{},AppWarnEnableParam:{}", user.getUsername(), request.toString());
        msWarnService.enable(request);
        return ResultUtil.success();
    }

    @RequiresPermissions("mach/warn/setting/add")
    @PostMapping("/rule/add")
    public Result ruleAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                          @RequestBody @Validated AppWarnRuleAddParam request) {
        logger.info("添加报警规则，loginer:{},:{}", user.getUsername(), request.toString());
        msWarnService.ruleAdd(request);
        return ResultUtil.success();
    }

    @RequiresPermissions("mach/warn/setting/edit")
    @PostMapping("/rule/edit")
    public Result ruleEdit(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                           @RequestBody @Validated AppWarnRuleEditParam request) {
        logger.info("编辑报警规则，loginer:{},AppWarnRuleEditParam:{}", user.getUsername(), request.toString());
        if (request.getRuleType() == 104 || request.getRuleType() == 105 || request.getRuleType() == 106) {
            try {
                int v = Integer.parseInt(request.getRuleValue());
                AssertUtil.isTrue(v <= 0, "时长只能设置为正整数");
            } catch (Exception e) {
                AssertUtil.throwsException("时长只能设置为正整数");
            }
        }
        msWarnService.ruleEdit(request);
        return ResultUtil.success();
    }

    @GetMapping("/object/list")
    public Result objectList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("ruleId") Integer ruleId) {
        logger.info("查找报警规则下的设备，loginer:{},ruleId:{}", user.getUsername(), ruleId);
        ListData<AppMachDTO> pageData = msWarnService.objectList(ruleId);
        return ResultUtil.success(pageData);
    }

    @RequiresPermissions("mach/warn/setting/machList")
    @PostMapping("/object/add")
    public Result objectAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                            @RequestBody @Validated AppWarnMachAddParam request) {
        logger.info("添加报警对象，loginer:{},AppWarnMachAddParam:{}", user.getUsername(), request.toString());
        msWarnService.objectAdd(request);
        return ResultUtil.success();
    }

    @GetMapping("/getMachList")
    public Result getMachList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                              @RequestParam("ruleId") Integer ruleId) {
        logger.info("获取可添加报警的的设备列表，loginer:{},ruleId:{}", user.getUsername(), ruleId);
        ListData<AppMachDTO> listData = msWarnService.getMachList(ruleId);
        return ResultUtil.success(listData);
    }

    @RequiresPermissions("mach/warn/setting/time")
    @PostMapping("/rule/setTime")
    public Result setTime(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                          @RequestBody @Validated AppWarnSetTimeParam request) {
        logger.info("设置报警时间，loginer:{},AppWarnSetTimeParam:{}", user.getUsername(), request.toString());
        msWarnService.setTime(request);
        return ResultUtil.success();
    }

    @GetMapping("/user/list")
    public Result userList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                           @RequestParam("ruleId") Integer ruleId) {
        logger.info("获取接收报警消息的用户列表，loginer:{},ruleId:{}", user.getUsername(), ruleId);
        AppWarnMsgRecDTO appWarnMsgRecDTO = msWarnService.userList(ruleId);
        return ResultUtil.success(appWarnMsgRecDTO);
    }

    @RequiresPermissions("mach/warn/setting/user")
    @PostMapping("/user/add")
    public Result userAdd(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                          @RequestBody @Validated AppWarnSetUserParam request) {
        logger.info("设置报警消息接收人,loginer:{},AppWarnSetUserParam:{}", user.getUsername(), request.toString());
        msWarnService.userAdd(request);
        return ResultUtil.success();
    }

    @GetMapping("/record/list")
    public Result recordList(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                             @RequestParam("pageNum") Integer pageNum,
                             @RequestParam("pageSize") Integer pageSize,
                             @RequestParam(value = "deptId") Integer deptId,
                             @RequestParam(value = "state", required = false) Integer state,
                             @RequestParam(value = "ruleType", required = false) Integer ruleType,
                             @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "startDate", required = false) Date startDate,
                             @DateTimeFormat(pattern = "yyyy-MM-dd") @RequestParam(value = "endDate", required = false) Date endDate) {
        logger.info("获取设备报警记录列表，loginer:{},pageNum:{},pageSize:{},deptId:{},state:{},ruleType:{},startDate:{},endDate:{}",
                user.getUsername(), pageNum, pageSize, deptId, state, ruleType, startDate, endDate);
        Date startTime = null;
        Date endTime = null;
        if (startDate != null) {
            startTime = DateUtil.getDateBegin(startDate);
        }
        if (endDate != null) {
            endTime = DateUtil.getDateEnd(endDate);
        }
        PageData<AppWarnMachRecordDTO> pageData = msWarnService.recordList(pageNum, pageSize, deptId, state, ruleType, startTime, endTime);
        return ResultUtil.success(pageData);
    }

    @RequiresPermissions("mach/warn/record/manage")
    @PostMapping("/record/handle")
    public Result recordHandle(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                               @RequestBody @Validated AppWarnHandleParam request) {
        logger.info("处理设备报警，loginer:{},AppWarnHandleParam:{}", user.getUsername(), request.toString());
        msWarnService.recordHandle(user, request);
        return ResultUtil.success();
    }

    @RequiresPermissions("mach/warn/record/manage")
    @PostMapping("/record/batchHandle")
    public Result batchHandle(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                              @RequestBody @Validated AppWarnBatchHandleParam param) {
        logger.info("批量处理设备报警，loginer:{},AppWarnBatchHandleParam:{}", user.getUsername(), param.toString());
        param.setUserId(user.getId());
        param.setPhone(user.getPhone());
        param.setUserName(user.getNickname());
        msWarnService.batchHandle(param);
        return ResultUtil.success();
    }

    @PostMapping("/record/del")
    public Result del(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                      @RequestBody @Validated AppWarnBatchDelParam param) {
        logger.info("批量删除设备报警，loginer:{},AppWarnBatchDelParam:{}", user.getUsername(), param.toString());
        msWarnService.del(param);
        return ResultUtil.success();
    }

    @GetMapping("/record/detail")
    public Result recordDetail(@SessionAttribute(SessionAttr.MS_USER) SysUser user,
                               @RequestParam("id") Integer id) {
        logger.info("设备报警详情，loginer:{},id:{}", user.getUsername(), id);
        AppWarnDetailDTO warnMachDetaiDTO = msWarnService.recordDetail(id);
        return ResultUtil.success(warnMachDetaiDTO);

    }

}
